package com.dongge.interceptor;

import com.dongge.entity.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.struts2.StrutsStatics;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 权限拦截器工作过程
 * 拦住每一个进入拦截器的URL
 * 如果用户已经登录查找该用户是否有访问该链接的权限
 * 检查方法如下：
 * 如果该链接在权限表中，那么检查该用户是否有权限，要是有才能放行
 * 如果该链接不在权限表中，那直接放行
 * 如果用户没有登录
 * 检查链接是否为登录链接 如果是就立即放行
 * 难点：如何获取链接
 */
public class RightInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        String result = "NO_PERMISSION";
        ActionContext actionContext = invocation.getInvocationContext();
        Map<String,Object> session = actionContext.getSession();
//        HttpServletRequest request = (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST);
//        StringBuffer url = request.getRequestURL();
        String url = invocation.getProxy().getNamespace()+invocation.getProxy().getActionName();
        List<String> rightList = (List)actionContext.getApplication().get("RIGHTLIST");
        User user = (User)session.get("user");
        if(user == null){
            if(url.indexOf("login")!=-1)
                result = invocation.invoke();
            else
                result = "LOGIN";
        }
        else {
            //只有在url在列表中才能进行权限判断
            //对于不在权限列表中的url直接给予放行
            if(rightList.contains(url)){
                if (user.hasPermission(url)) {
                    result = invocation.invoke();
                }
            }
            else {
                result = invocation.invoke();
            }


        }
        return result;
    }
}
